package com.paishen.peiniwan.module.profile;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.paishen.common.dialog.LoadingDialog;
import com.paishen.common.dialog.SelectionDialog;
import com.paishen.common.dialog.picker.DataPickerDialog;
import com.paishen.common.dialog.picker.DictPickerDialog;
import com.paishen.common.util.BaseUtil;
import com.paishen.common.widget.TitleLayout;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.BusEvent;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.database.AuthInfoDao;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.entity.UserMiscInfo;
import com.paishen.peiniwan.frame.http.entity.UserTag;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.squareup.okhttp.Request;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import de.greenrobot.event.EventBus;

public class ProfileInfoEditActivity extends BaseActivity {
    private TextView txHeight, txWeight, txAge, txProfession, txEducation, txConstellation, txSalary, txAddress;
    private ImageView imgAvatar;
    private ViewGroup layHobbyValue, laySpecialtyValue, layAbilityValue;
    private TextView txHobbyAdd, txSpecialtyAdd, txAbilityAdd;
    private EditText edNickname;
    private TextView txIntro;

    private AlertDialog dlgSubmitRemind;
    private SelectionDialog dlgGetPhoto;
    private DictPickerDialog dlgAddress;
    private DataPickerDialog dlgHeight, dlgWeight, dlgAge, dlgProfession, dlgEducation, dlgConstellation, dlgSalary;
    private ProfileTagEditDialog dlgHobby, dlgSpecialty, dlgAbility;


    private static final int REQUEST_CODE_SIGN = 542;

    /**
     * 兴趣爱好
     */
    private String[] arrHobby;
    /**
     * 一技之长
     */
    private String[] arrSpecialty;
    /**
     * 性格特征
     */
    private String[] arrAbility;

    private String uploadAvatarImageUrl;

    private boolean isEditMode;

    private boolean checkIsChanged() {
        com.paishen.peiniwan.database.User user = App.i().getUser();
        if (!TextUtils.isEmpty(uploadAvatarImageUrl)) return true;
        if (!TextUtils.equals(user.getNickname(), edNickname.getText().toString())) return true;
        final String intro = !TextUtils.isEmpty(txIntro.getText()) ? txIntro.getText().toString() : getString(R.string.profile_intro_tips);
        if (!TextUtils.equals(user.getIntro(), intro)) return true;
        if (!TextUtils.equals(user.getHeight(), txHeight.getText().toString())) return true;
        if (!TextUtils.equals(user.getWeight(), txWeight.getText().toString())) return true;
        if (!TextUtils.equals(user.getAge(), txAge.getText().toString())) return true;
        if (!TextUtils.equals(user.getProfession(), txProfession.getText().toString())) return true;
        if (!TextUtils.equals(user.getDegree(), txEducation.getText().toString())) return true;
        if (!TextUtils.equals(user.getConstellation(), txConstellation.getText().toString()))
            return true;
        if (!TextUtils.equals(user.getCity(), txAddress.getText().toString())) return true;
        if (!TextUtils.equals(user.getSalary(), txSalary.getText().toString())) return true;

        List<UserTag> tagList = new ArrayList<>();
        tagList.add(new UserTag(arrHobby));
        tagList.add(new UserTag(arrSpecialty));
        tagList.add(new UserTag(arrAbility));
        final String tags = new String(Base64.encode(App.i().getGson().toJson(tagList).getBytes(), Base64.DEFAULT));
        return !TextUtils.equals(user.getTags(), tags);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_info_edit);

        findViewById(R.id.lay_container).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BaseUtil.hideSoftInputFromWindowAlways(ProfileInfoEditActivity.this);
            }
        });

        TitleLayout layTitle = (TitleLayout) findViewById(R.id.lay_title);
        TextView viewSave = (TextView) LayoutInflater.from(this).inflate(R.layout.layout_title_menu_text, null);
        viewSave.setText(R.string.save);
        ImageView viewBack = (ImageView) LayoutInflater.from(this).inflate(R.layout.layout_title_menu_image, null);
        viewBack.setImageResource(R.mipmap.common_back);
        viewBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkIsChanged()) {
                    showSubmitRemindDialog();
                } else {
                    onBackPressed();
                }
            }
        });
        layTitle.pushContent(viewBack, getString(R.string.profile_edit), viewSave, false);
        viewSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkIsChanged()) {
                    if (checkUserInfo()) {
                        requestUserUpdateProfile();
                    }
                } else {
                    onBackPressed();
                }
            }
        });

        View.OnClickListener onClickListener = new View.OnClickListener() {
            private long timestamp;
            @Override
            public void onClick(View v) {
                long curr = System.currentTimeMillis();
                if (curr - timestamp < 500) return;
                timestamp = curr;

                BaseUtil.hideSoftInputFromWindowAlways(ProfileInfoEditActivity.this);
                switch (v.getId()) {
                    case R.id.lay_head:
                        showGetPhotoDialog();
                        break;
                    case R.id.lay_sign:
                        Intent intentSign = new Intent(ProfileInfoEditActivity.this, ProfileInfoEditSignActivity.class);
                        intentSign.putExtra(ProfileInfoEditSignActivity.EXTRA_SIGN_CONTENT, txIntro.getText().toString());
                        startActivityForResult(intentSign, REQUEST_CODE_SIGN);
                        break;
                    case R.id.lay_height:
                        showHeightDialog();
                        break;
                    case R.id.lay_weight:
                        showWeightDialog();
                        break;
                    case R.id.lay_age:
                        showAgeDialog();
                        break;
                    case R.id.lay_profession:
                        showProfessionDialog();
                        break;
                    case R.id.lay_education:
                        showEducationDialog();
                        break;
                    case R.id.lay_constellation:
                        showConstellationDialog();
                        break;
                    case R.id.lay_salary:
                        showSalaryDialog();
                        break;
                    case R.id.lay_address:
                        showAddressDialog();
                        break;
                    case R.id.lay_hobby:
                        showHobbyDialog();
                        break;
                    case R.id.lay_specialty:
                        showSpecialtyDialog();
                        break;
                    case R.id.lay_ability:
                        showAbilityDialog();
                        break;
                }
            }
        };

        findViewById(R.id.lay_head).setOnClickListener(onClickListener);
        findViewById(R.id.lay_sign).setOnClickListener(onClickListener);
        findViewById(R.id.lay_height).setOnClickListener(onClickListener);
        findViewById(R.id.lay_weight).setOnClickListener(onClickListener);
        findViewById(R.id.lay_age).setOnClickListener(onClickListener);
        findViewById(R.id.lay_profession).setOnClickListener(onClickListener);
        findViewById(R.id.lay_education).setOnClickListener(onClickListener);
        findViewById(R.id.lay_constellation).setOnClickListener(onClickListener);
        findViewById(R.id.lay_salary).setOnClickListener(onClickListener);
        findViewById(R.id.lay_address).setOnClickListener(onClickListener);
        findViewById(R.id.lay_hobby).setOnClickListener(onClickListener);
        findViewById(R.id.lay_specialty).setOnClickListener(onClickListener);
        findViewById(R.id.lay_ability).setOnClickListener(onClickListener);

        layHobbyValue = (ViewGroup) findViewById(R.id.lay_hobby_value);
        laySpecialtyValue = (ViewGroup) findViewById(R.id.lay_specialty_value);
        layAbilityValue = (ViewGroup) findViewById(R.id.lay_ability_value);
        txHobbyAdd = (TextView) findViewById(R.id.tx_hobby_add);
        txSpecialtyAdd = (TextView) findViewById(R.id.tx_specialty_add);
        txAbilityAdd = (TextView) findViewById(R.id.tx_ability_add);

        txHeight = (TextView) findViewById(R.id.tx_height);
        txWeight = (TextView) findViewById(R.id.tx_weight);
        txAge = (TextView) findViewById(R.id.tx_age);
        txProfession = (TextView) findViewById(R.id.tx_profession);
        txEducation = (TextView) findViewById(R.id.tx_education);
        txConstellation = (TextView) findViewById(R.id.tx_constellation);
        txSalary = (TextView) findViewById(R.id.tx_salary);
        txAddress = (TextView) findViewById(R.id.tx_address);

        edNickname = (EditText) findViewById(R.id.ed_nickname);
        txIntro = (TextView) findViewById(R.id.tx_intro);

        imgAvatar = (ImageView) findViewById(R.id.img_avatar);

        View.OnFocusChangeListener editInputFocusChangeListener = new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // first click
                    isEditMode = true;
                }
            }
        };
        View.OnClickListener editInputClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isEditMode = true;
            }
        };

        edNickname.setOnClickListener(editInputClickListener);
        txIntro.setOnClickListener(editInputClickListener);
        edNickname.setOnFocusChangeListener(editInputFocusChangeListener);
        txIntro.setOnFocusChangeListener(editInputFocusChangeListener);
        txIntro.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isEditMode = true;
            }
        });
        ScrollView viewScroll = (ScrollView) findViewById(R.id.view_scroll);
        viewScroll.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isEditMode) {
                    isEditMode = false;
                    BaseUtil.hideSoftInputFromWindowAlways(ProfileInfoEditActivity.this);
                }
                return false;
            }
        });

        // requestUserInfo();
        initData();
    }

    private boolean checkUserInfo() {
        boolean result = true;
        if (edNickname.getText().length() < 2) {
            result = false;
            BaseUtil.showToast(R.string.register_fail_nickname_5);
        } else if (TextUtils.isEmpty(txAddress.getText())) {
            result = false;
            BaseUtil.showToast(R.string.register_input_city);
        } else if (TextUtils.isEmpty(txAge.getText())) {
            result = false;
            BaseUtil.showToast(R.string.register_input_age);
        }
        return result;
    }

    private void initData() {
        com.paishen.peiniwan.database.User user = App.i().getUser();


        Glide.with(this).load(user.getHead_img_url()).bitmapTransform(App.i().getCropCircleTransformation()).into(imgAvatar);
        edNickname.setText(user.getNickname());
        if (!TextUtils.isEmpty(user.getIntro())) txIntro.setText(user.getIntro());
        if (!TextUtils.isEmpty(user.getHeight())) txHeight.setText(user.getHeight());
        if (!TextUtils.isEmpty(user.getWeight())) txWeight.setText(user.getWeight());
        if (!TextUtils.isEmpty(user.getAge())) txAge.setText(user.getAge());
        if (!TextUtils.isEmpty(user.getProfession())) txProfession.setText(user.getProfession());
        if (!TextUtils.isEmpty(user.getDegree())) txEducation.setText(user.getDegree());
        if (!TextUtils.isEmpty(user.getConstellation()))
            txConstellation.setText(user.getConstellation());
        if (!TextUtils.isEmpty(user.getCity())) txAddress.setText(user.getCity());
        if (!TextUtils.isEmpty(user.getSalary())) txSalary.setText(user.getSalary());

        if (!TextUtils.isEmpty(user.getTags())) {
            List<UserTag> userTagList = App.i().getGson().fromJson(new String(Base64.decode(user.getTags(), Base64.DEFAULT)), new TypeToken<List<UserTag>>() {
            }.getType());
            arrHobby = userTagList.get(0).tag_name;
            arrSpecialty = userTagList.get(1).tag_name;
            arrAbility = userTagList.get(2).tag_name;
        }
        fillTheTagView(arrHobby, txHobbyAdd, layHobbyValue, R.drawable.profile_info_shape_tag_hobby);
        fillTheTagView(arrSpecialty, txSpecialtyAdd, laySpecialtyValue, R.drawable.profile_info_shape_tag_specialty);
        fillTheTagView(arrAbility, txAbilityAdd, layAbilityValue, R.drawable.profile_info_shape_tag_ability);
    }

    private void fillTheTagView(String[] items, View hide, ViewGroup show, int backgroundRes) {
        if (items.length > 0) {
            hide.setVisibility(View.GONE);
            show.setVisibility(View.VISIBLE);
            show.removeAllViewsInLayout();
            for (String i : items) {
                show.addView(makeTagView(i, backgroundRes));
            }
        } else {
            hide.setVisibility(View.VISIBLE);
            show.setVisibility(View.GONE);
        }
    }


    private void requestUserUpdateProfile() {
        final String nickname = edNickname.getText().toString();
        final String intro = !TextUtils.isEmpty(txIntro.getText()) ? txIntro.getText().toString() : getString(R.string.profile_intro_tips);

        List<UserTag> tagList = new ArrayList<>();
        tagList.add(new UserTag(arrHobby));
        tagList.add(new UserTag(arrSpecialty));
        tagList.add(new UserTag(arrAbility));
        final String tags = new String(Base64.encode(App.i().getGson().toJson(tagList).getBytes(), Base64.DEFAULT));

        File photo = null;
        final String mUploadHeadImageUrl = uploadAvatarImageUrl;
        if (!TextUtils.isEmpty(mUploadHeadImageUrl)) photo = new File(mUploadHeadImageUrl);

        final String height = txHeight.getText().toString();
        final String weight = txWeight.getText().toString();
        final String age = txAge.getText().toString();
        final String profession = txProfession.getText().toString();
        final String degree = txEducation.getText().toString();
        final String constellation = txConstellation.getText().toString();
        final String city = txAddress.getText().toString();
        final String salary = txSalary.getText().toString();

        final LoadingDialog dlgLoading = new LoadingDialog.Builder(this).create();
        dlgLoading.show();
        PnwHttpManager.User.updateProfile(TAG, nickname, intro, tags, photo, height, weight, age, profession, degree, constellation, city, salary, new PnwOkCallbackAdapter<HttpRespData<UserMiscInfo>>() {
            @Override
            public void onResponse(HttpRespData<UserMiscInfo> response, boolean fresh) {
                super.onResponse(response, fresh);
                dlgLoading.dismiss();
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    com.paishen.peiniwan.database.User user = App.i().getUser();
                    if (!TextUtils.isEmpty(mUploadHeadImageUrl)) {
                        user.setHead_img_url(response.data.head_img_url);
                        BaseUtil.showToast(R.string.auth_profile_update_avatar);

                        if (response.data.auth != null) {
                            AuthInfoDao authInfoDao = App.i().getCurrDaoSession().getAuthInfoDao();
                            com.paishen.peiniwan.database.AuthInfo dbAuthInfo = authInfoDao.queryBuilder().where(AuthInfoDao.Properties.UserId.eq(App.i().getUser().getId())).unique();
                            if (dbAuthInfo != null) {
                                dbAuthInfo.setStatus(response.data.auth.status);
                                authInfoDao.insertOrReplace(dbAuthInfo);
                                EventBus.getDefault().post(new BusEvent(BusEvent.ACTION_MAIN_PROFILE_AUTH_SUBMIT));
                            }
                        }
                    }

                    user.setNickname(nickname);
                    user.setIntro(intro);
                    user.setTags(tags);
                    user.setHeight(height);
                    user.setWeight(weight);
                    user.setProfession(profession);
                    user.setCity(city);
                    user.setAge(age);
                    user.setDegree(degree);
                    user.setConstellation(constellation);
                    user.setSalary(salary);

                    EventBus.getDefault().post(new BusEvent(BusEvent.TYPE_BACKGROUND, BusEvent.ACTION_DB_UPDATE_USER, user));
                    EventBus.getDefault().post(new BusEvent(BusEvent.ACTION_REFRESH_MAIN_PROFILE));
                    finish();
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                dlgLoading.dismiss();
            }
        });
    }


    private void showGetPhotoDialog() {
        if (dlgGetPhoto == null) {
            List<SelectionDialog.Menu> menuList = new ArrayList<>();
            menuList.add(new SelectionDialog.Menu(getString(R.string.frame_photo_from_camera), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openCamera();
                    dlgGetPhoto.dismiss();
                }
            }));

            menuList.add(new SelectionDialog.Menu(getString(R.string.frame_photo_from_album), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openPhotos();
                    dlgGetPhoto.dismiss();
                }
            }));
            dlgGetPhoto = new SelectionDialog.Builder(this).setMenuList(menuList).create();
        }

        dlgGetPhoto.show();
    }

    private void showHeightDialog() {
        if (dlgHeight == null) {
            List<String> data = new ArrayList<>();
            data.addAll(d(150, 70, "cm"));

            dlgHeight = new DataPickerDialog.Builder(this).setTitle(getString(R.string.profile_height)).setSelection(21).setUnit("").setData(data)
                    .setOnDataSelectedListener(new DataPickerDialog.OnDataSelectedListener() {
                        @Override
                        public void onDataSelected(String itemValue) {
                            txHeight.setText(itemValue);
                        }
                    }).create();
        }
        if (!TextUtils.isEmpty(txHeight.getText()))
            dlgHeight.setSelection(txHeight.getText().toString());
        dlgHeight.show();
    }

    private void showWeightDialog() {
        if (dlgWeight == null) {
            List<String> data = new ArrayList<>();
            data.addAll(d(40, 50, "kg"));

            dlgWeight = new DataPickerDialog.Builder(this).setTitle(getString(R.string.profile_weight)).setSelection(16).setUnit("").setData(data).
                    setOnDataSelectedListener(new DataPickerDialog.OnDataSelectedListener() {
                        @Override
                        public void onDataSelected(String itemValue) {
                            txWeight.setText(itemValue);
                        }
                    }).create();
        }
        if (!TextUtils.isEmpty(txWeight.getText()))
            dlgWeight.setSelection(txWeight.getText().toString());
        dlgWeight.show();
    }

    private void showAgeDialog() {
        if (dlgAge == null) {
            List<String> data = new ArrayList<>();
            data.addAll(d(18, 22, getString(R.string.profile_age_unit)));
            dlgAge = new DataPickerDialog.Builder(this).setTitle(getString(R.string.profile_age)).setSelection(7).setUnit("").setData(data)
                    .setOnDataSelectedListener(new DataPickerDialog.OnDataSelectedListener() {
                        @Override
                        public void onDataSelected(String itemValue) {
                            txAge.setText(itemValue);
                        }
                    }).create();
        }
        if (!TextUtils.isEmpty(txAge.getText())) dlgAge.setSelection(txAge.getText().toString());
        dlgAge.show();
    }

    private void showProfessionDialog() {
        if (dlgProfession == null) {
            List<String> data = Arrays.asList(getResources().getStringArray(R.array.profile_profession));
            dlgProfession = new DataPickerDialog.Builder(this).setTitle(getString(R.string.profile_profession)).setUnit("").setData(data)
                    .setOnDataSelectedListener(new DataPickerDialog.OnDataSelectedListener() {
                        @Override
                        public void onDataSelected(String itemValue) {
                            txProfession.setText(itemValue);
                        }
                    }).create();
        }
        if (!TextUtils.isEmpty(txProfession.getText()))
            dlgProfession.setSelection(txProfession.getText().toString());
        dlgProfession.show();
    }

    private void showEducationDialog() {
        if (dlgEducation == null) {
            List<String> data = Arrays.asList(getResources().getStringArray(R.array.profile_education));
            dlgEducation = new DataPickerDialog.Builder(this).setTitle(getString(R.string.profile_education)).setUnit("").setData(data).
                    setOnDataSelectedListener(new DataPickerDialog.OnDataSelectedListener() {
                        @Override
                        public void onDataSelected(String itemValue) {
                            txEducation.setText(itemValue);
                        }
                    }).create();
        }
        if (!TextUtils.isEmpty(txEducation.getText()))
            dlgEducation.setSelection(txEducation.getText().toString());
        dlgEducation.show();
    }

    private void showConstellationDialog() {
        if (dlgConstellation == null) {
            List<String> data = Arrays.asList(getResources().getStringArray(R.array.profile_constellation));
            dlgConstellation = new DataPickerDialog.Builder(this).setTitle(getString(R.string.profile_constellation)).setUnit("").setData(data)
                    .setOnDataSelectedListener(new DataPickerDialog.OnDataSelectedListener() {
                        @Override
                        public void onDataSelected(String itemValue) {
                            txConstellation.setText(itemValue);
                        }
                    }).create();
        }
        if (!TextUtils.isEmpty(txConstellation.getText()))
            dlgConstellation.setSelection(txConstellation.getText().toString());
        dlgConstellation.show();
    }

    private void showSalaryDialog() {
        if (dlgSalary == null) {
            List<String> data = Arrays.asList(getResources().getStringArray(R.array.profile_salary));
            dlgSalary = new DataPickerDialog.Builder(this).setTitle(getString(R.string.profile_constellation)).setUnit("").setData(data)
                    .setOnDataSelectedListener(new DataPickerDialog.OnDataSelectedListener() {
                        @Override
                        public void onDataSelected(String itemValue) {
                            txSalary.setText(itemValue);
                        }
                    }).create();
        }
        if (!TextUtils.isEmpty(txSalary.getText()))
            dlgSalary.setSelection(txSalary.getText().toString());
        dlgSalary.show();
    }

    private void showAddressDialog() {
        if (dlgAddress == null) {
            dlgAddress = new DictPickerDialog.Builder(this).setOnDictSelectedListener(new DictPickerDialog.OnDictSelectedListener() {
                @Override
                public void onDictSelected(String[] itemValue) {
                    txAddress.setText(itemValue[0] + "-" + itemValue[1]);
                }
            }).create();
        }
        dlgAddress.show();
    }

    private int find(String target, String[] source) {
        for (int i = 0; i < source.length; i++) {
            if (TextUtils.equals(target, source[i])) return i;
        }
        return -1;
    }

    private String[] merge(String mCurrValue[], String[] preset) {
        final String[] finalResult;
        if (mCurrValue != null) {
            final String[] mCustom = new String[mCurrValue.length];
            int mCustomIndex = 0;
            for (String mHobby : mCurrValue) {
                if (find(mHobby, preset) < 0) {
                    mCustom[mCustomIndex] = mHobby;
                    mCustomIndex++;
                }
            }
            finalResult = new String[preset.length + mCustomIndex];
            System.arraycopy(mCustom, 0, finalResult, 0, mCustomIndex);
            System.arraycopy(preset, 0, finalResult, mCustomIndex, finalResult.length - mCustomIndex);
        } else {
            finalResult = preset;
        }
        return finalResult;
    }

    private TextView makeTagView(String text, int backgroundRes) {
        TextView t = new TextView(this);
        t.setText(text);
        t.setTextColor(0xffffffff);
        t.setBackgroundResource(backgroundRes);
        ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        final int spacing = BaseUtil.dip2px(10);
        lp.setMargins(spacing, 0, 0, spacing);
        t.setLayoutParams(lp);
        t.setPadding(spacing, spacing / 2, spacing, spacing / 2);
        return t;
    }

    private void showHobbyDialog() {

        final String[] arrayData = getResources().getStringArray(
                App.i().getUser().getGender() ?
                        R.array.profile_hobby_male : R.array.profile_hobby_female);
        final String[] finalResult = merge(arrHobby, arrayData);
        final boolean[] finalResultSelected = new boolean[finalResult.length];
        if (arrHobby != null) {
            for (String anArrHobby : arrHobby) {
                int findResult = find(anArrHobby, finalResult);
                if (findResult >= 0) finalResultSelected[findResult] = true;
            }
        }


        dlgHobby = new ProfileTagEditDialog.Builder(this).setTitle(R.string.profile_hobby_add).setMultiChoiceItems(finalResult, finalResultSelected,
                new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        finalResultSelected[which] = isChecked;
                    }
                }).setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String[] mFinalResult = new String[finalResult.length];
                int index = 0;
                for (int i = 0; i < finalResultSelected.length; i++) {
                    if (finalResultSelected[i]) {
                        mFinalResult[index] = finalResult[i];
                        index++;
                    }
                }
                fillTheTagView(arrHobby = Arrays.copyOfRange(mFinalResult, 0, index), txHobbyAdd, layHobbyValue, R.drawable.profile_info_shape_tag_hobby);
                dlgHobby.dismiss();
            }
        }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dlgHobby.dismiss();
            }
        }).create();

        dlgHobby.show();
    }


    private void showSpecialtyDialog() {

        final String[] arrayData = getResources().getStringArray(
                App.i().getUser().getGender() ?
                        R.array.profile_specialty_male : R.array.profile_specialty_female);
        final String[] finalResult = merge(arrSpecialty, arrayData);
        final boolean[] finalResultSelected = new boolean[finalResult.length];
        if (arrSpecialty != null) {
            for (String anArrSpecialty : arrSpecialty) {
                int findResult = find(anArrSpecialty, finalResult);
                if (findResult >= 0) finalResultSelected[findResult] = true;
            }
        }


        dlgSpecialty = new ProfileTagEditDialog.Builder(this).setTitle(R.string.profile_specialty_add).setMultiChoiceItems(finalResult, finalResultSelected,
                new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        finalResultSelected[which] = isChecked;
                    }
                }).setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String[] mFinalResult = new String[finalResult.length];
                int index = 0;
                for (int i = 0; i < finalResultSelected.length; i++) {
                    if (finalResultSelected[i]) {
                        mFinalResult[index] = finalResult[i];
                        index++;
                    }
                }
                fillTheTagView(arrSpecialty = Arrays.copyOfRange(mFinalResult, 0, index), txSpecialtyAdd, laySpecialtyValue, R.drawable.profile_info_shape_tag_specialty);
                dlgSpecialty.dismiss();

            }
        }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dlgSpecialty.dismiss();
            }
        }).create();

        dlgSpecialty.show();
    }


    private void showAbilityDialog() {

        final String[] arrayData = getResources().getStringArray(
                App.i().getUser().getGender() ?
                        R.array.profile_ability_male : R.array.profile_ability_female);
        final String[] finalResult = merge(arrAbility, arrayData);
        final boolean[] finalResultSelected = new boolean[finalResult.length];
        if (arrAbility != null) {
            for (String anArrAbility : arrAbility) {
                int findResult = find(anArrAbility, finalResult);
                if (findResult >= 0) finalResultSelected[findResult] = true;
            }
        }

        dlgAbility = new ProfileTagEditDialog.Builder(this).setTitle(R.string.profile_ability_add).setMultiChoiceItems(finalResult, finalResultSelected,
                new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        finalResultSelected[which] = isChecked;
                    }
                }).setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String[] mFinalResult = new String[finalResult.length];
                int index = 0;
                for (int i = 0; i < finalResultSelected.length; i++) {
                    if (finalResultSelected[i]) {
                        mFinalResult[index] = finalResult[i];
                        index++;
                    }
                }
                fillTheTagView(arrAbility = Arrays.copyOfRange(mFinalResult, 0, index), txAbilityAdd, layAbilityValue, R.drawable.profile_info_shape_tag_ability);
                dlgAbility.dismiss();
            }
        }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dlgAbility.dismiss();
            }
        }).create();

        dlgAbility.show();
    }


    /**
     * 将数字传化为集合，并且补充0
     *
     * @param startNum 数字起点
     * @param count    数字个数
     * @return 数字集合
     */
    private List<String> d(int startNum, int count, String unit) {
        String[] values = new String[count];
        for (int i = startNum; i < startNum + count; i++) {
            String tempValue = (i < 10 ? "0" : "") + i;
            values[i - startNum] = tempValue + unit;
        }
        return Arrays.asList(values);
    }

    public void onEventMainThread(com.paishen.peiniwan.BusEvent event) {
        super.onEventMainThread(event);

        if (event.type == BusEvent.TYPE_MAIN_THREAD) {
            switch (event.action) {
                case BusEvent.ACTION_PICTURE_QUERY_OUT:
                    uploadAvatarImageUrl = String.valueOf(event.content);
                    Glide.with(this).load(uploadAvatarImageUrl).bitmapTransform(App.i().getCropCircleTransformation()).into(imgAvatar);
                    break;
            }
        }
    }

    private void showSubmitRemindDialog() {
        if (dlgSubmitRemind == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.tips).setMessage(R.string.profile_edit_save_changed).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dlgSubmitRemind.dismiss();
                    finish();
                }
            }).setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dlgSubmitRemind.dismiss();
                    requestUserUpdateProfile();
                }
            });
            dlgSubmitRemind = builder.create();
        }
        dlgSubmitRemind.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_SIGN:
                    String signContent = data.getStringExtra(ProfileInfoEditSignActivity.EXTRA_SIGN_CONTENT);
                    txIntro.setText(signContent);
                    break;
            }
        }
    }
}
